/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewSimulPanel.java
 *
 * Created on 14 mars 2012, 20:38:07
 */
package kuti.grp5.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import kuti.ISimulParams;
import kuti.grp5.SimulParams;
import kuti.grp5.ui.SimulationPanel.GenerationType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * Shows a panel with various parameters necessary to start a simulation.
 * @author Jocelyn
 */
public class ParamPanel extends JDialog {

    private final JFrame owner;

    /** Creates new form NewSimulPanel */
    public ParamPanel(JFrame owner) {
        super(owner, false);
        this.owner = owner;
        owner.setVisible(false);
        initComponents();
        setLocationRelativeTo(this);
        setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pMain = new javax.swing.JPanel();
        pTitre = new javax.swing.JPanel();
        pTitleCombo = new javax.swing.JPanel();
        labTitre = new javax.swing.JLabel();
        cbDifficulty = new javax.swing.JComboBox();
        sepTitre = new javax.swing.JSeparator();
        pParams = new javax.swing.JPanel();
        pParamKuti = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        tfDiameter = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tfMaxEnergy = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tfInitEnergy = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        tfKutiSpeedCutterOff = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        tfMoveEnergy = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        tfRotationEnergy = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        tfMowEnergy = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        tfKutiSpeedCutterOn = new javax.swing.JTextField();
        pParamTools = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        tfNoiseFactor = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        tfRadarEnergy = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        tfMessageLength = new javax.swing.JTextField();
        pParamSimul = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        tfLawnMaxHeight = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        tfGrowthPeriod = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        tfScoreInterval = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        tfMaxStep = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        tfMagnetLibEnergy = new javax.swing.JTextField();
        pBts = new javax.swing.JPanel();
        btLaunchSimul = new javax.swing.JButton();
        loadXML = new javax.swing.JButton();
        btSaveXML = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        pMain.setLayout(new java.awt.BorderLayout());

        pTitre.setLayout(new javax.swing.BoxLayout(pTitre, javax.swing.BoxLayout.Y_AXIS));

        pTitleCombo.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        labTitre.setFont(new java.awt.Font("Verdana", 1, 24));
        labTitre.setText("Paramètres de la nouvelle simulation");
        pTitleCombo.add(labTitre);

        cbDifficulty.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Difficulté (optionnel)", "Bac à sable", "Facile", "Moyen", "Difficile", "Brutal" }));
        cbDifficulty.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbDifficultyActionPerformed(evt);
            }
        });
        pTitleCombo.add(cbDifficulty);

        pTitre.add(pTitleCombo);
        pTitre.add(sepTitre);

        pMain.add(pTitre, java.awt.BorderLayout.NORTH);

        pParams.setLayout(new javax.swing.BoxLayout(pParams, javax.swing.BoxLayout.LINE_AXIS));

        pParamKuti.setBorder(javax.swing.BorderFactory.createTitledBorder("Paramètres du Kuti"));
        pParamKuti.setLayout(new java.awt.GridBagLayout());

        jLabel1.setLabelFor(tfDiameter);
        jLabel1.setText("Diamètre");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel1, gridBagConstraints);

        tfDiameter.setColumns(5);
        tfDiameter.setText("50");
        tfDiameter.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfDiameter, gridBagConstraints);

        jLabel2.setLabelFor(tfDiameter);
        jLabel2.setText("Energie Max");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel2, gridBagConstraints);

        tfMaxEnergy.setColumns(5);
        tfMaxEnergy.setText("50000");
        tfMaxEnergy.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfMaxEnergy, gridBagConstraints);

        jLabel3.setLabelFor(tfDiameter);
        jLabel3.setText("Energie initiale");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel3, gridBagConstraints);

        tfInitEnergy.setColumns(5);
        tfInitEnergy.setText("40000");
        tfInitEnergy.setToolTipText("");
        tfInitEnergy.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfInitEnergy, gridBagConstraints);

        jLabel10.setLabelFor(tfDiameter);
        jLabel10.setText("Vitesse (sans tonte)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel10, gridBagConstraints);

        tfKutiSpeedCutterOff.setColumns(5);
        tfKutiSpeedCutterOff.setText("80");
        tfKutiSpeedCutterOff.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfKutiSpeedCutterOff, gridBagConstraints);

        jLabel11.setLabelFor(tfDiameter);
        jLabel11.setText("Energie de déplacement");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel11, gridBagConstraints);

        tfMoveEnergy.setColumns(5);
        tfMoveEnergy.setText("1");
        tfMoveEnergy.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfMoveEnergy, gridBagConstraints);

        jLabel12.setLabelFor(tfDiameter);
        jLabel12.setText("Energie de rotation");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel12, gridBagConstraints);

        tfRotationEnergy.setColumns(5);
        tfRotationEnergy.setText("0.1");
        tfRotationEnergy.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfRotationEnergy, gridBagConstraints);

        jLabel13.setLabelFor(tfDiameter);
        jLabel13.setText("Energie de la tonte");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 7;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel13, gridBagConstraints);

        tfMowEnergy.setColumns(5);
        tfMowEnergy.setText("500");
        tfMowEnergy.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 7;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfMowEnergy, gridBagConstraints);

        jLabel16.setLabelFor(tfDiameter);
        jLabel16.setText("Vitesse (avec tonte)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(jLabel16, gridBagConstraints);

        tfKutiSpeedCutterOn.setColumns(5);
        tfKutiSpeedCutterOn.setText("60");
        tfKutiSpeedCutterOn.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamKuti.add(tfKutiSpeedCutterOn, gridBagConstraints);

        pParams.add(pParamKuti);

        pParamTools.setBorder(javax.swing.BorderFactory.createTitledBorder("Paramètres Radar / Messages"));
        pParamTools.setLayout(new java.awt.GridBagLayout());

        jLabel4.setLabelFor(tfDiameter);
        jLabel4.setText("Facteur de bruit du radar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamTools.add(jLabel4, gridBagConstraints);

        tfNoiseFactor.setColumns(5);
        tfNoiseFactor.setText("0.2");
        tfNoiseFactor.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamTools.add(tfNoiseFactor, gridBagConstraints);

        jLabel5.setLabelFor(tfDiameter);
        jLabel5.setText("Energie radar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamTools.add(jLabel5, gridBagConstraints);

        tfRadarEnergy.setColumns(5);
        tfRadarEnergy.setText("500");
        tfRadarEnergy.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamTools.add(tfRadarEnergy, gridBagConstraints);

        jLabel6.setLabelFor(tfDiameter);
        jLabel6.setText("Taille d'un message (Byte)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamTools.add(jLabel6, gridBagConstraints);

        tfMessageLength.setColumns(5);
        tfMessageLength.setText("500");
        tfMessageLength.setMinimumSize(new java.awt.Dimension(6, 30));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamTools.add(tfMessageLength, gridBagConstraints);

        pParams.add(pParamTools);

        pParamSimul.setBorder(javax.swing.BorderFactory.createTitledBorder("Paramètres de la simulation"));
        pParamSimul.setLayout(new java.awt.GridBagLayout());

        jLabel7.setLabelFor(tfDiameter);
        jLabel7.setText("Hauteur max du gazon");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(jLabel7, gridBagConstraints);

        tfLawnMaxHeight.setColumns(5);
        tfLawnMaxHeight.setText("100");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(tfLawnMaxHeight, gridBagConstraints);

        jLabel8.setLabelFor(tfDiameter);
        jLabel8.setText("Période de croissance du gazon");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(jLabel8, gridBagConstraints);

        tfGrowthPeriod.setColumns(5);
        tfGrowthPeriod.setText("5");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(tfGrowthPeriod, gridBagConstraints);

        jLabel9.setLabelFor(tfDiameter);
        jLabel9.setText("Intervalle de score");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(jLabel9, gridBagConstraints);

        tfScoreInterval.setColumns(5);
        tfScoreInterval.setText("10");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(tfScoreInterval, gridBagConstraints);

        jLabel14.setLabelFor(tfDiameter);
        jLabel14.setText("Pas maximum");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(jLabel14, gridBagConstraints);

        tfMaxStep.setColumns(5);
        tfMaxStep.setText("1000");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(tfMaxStep, gridBagConstraints);

        jLabel15.setLabelFor(tfDiameter);
        jLabel15.setText("Energie pour libération d'un magnet.");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(jLabel15, gridBagConstraints);

        tfMagnetLibEnergy.setColumns(5);
        tfMagnetLibEnergy.setText("100");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
        pParamSimul.add(tfMagnetLibEnergy, gridBagConstraints);

        pParams.add(pParamSimul);

        pMain.add(pParams, java.awt.BorderLayout.CENTER);

        btLaunchSimul.setText("Lancer");
        btLaunchSimul.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLaunchSimulActionPerformed(evt);
            }
        });
        pBts.add(btLaunchSimul);

        loadXML.setText("Charger");
        loadXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadXMLActionPerformed(evt);
            }
        });
        pBts.add(loadXML);

        btSaveXML.setText("Sauver");
        btSaveXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSaveXMLActionPerformed(evt);
            }
        });
        pBts.add(btSaveXML);

        btCancel.setText("Annuler");
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });
        pBts.add(btCancel);

        pMain.add(pBts, java.awt.BorderLayout.PAGE_END);

        getContentPane().add(pMain, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Event triggered when the XML Load button is pressed.
     * Opens a JFileChooser that asks for an XML document. It then sets the
     * textfields in the parameters panel according to what it finds in the XML
     * file. If a field isn't found, the textfield is left blank.
     * @param evt - Event triggered
     */
    private void loadXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadXMLActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("XML", "xml"));

        if (fileChooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) {
            return;
        }

        setParametersFromXMLDoc(null,fileChooser.getSelectedFile());
    }//GEN-LAST:event_loadXMLActionPerformed

    /**
     * Event triggered when the Cancele button is pressed in the parameters panel.
     * It simply closes the window.
     * @param evt  - Event triggered
     */
    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
        setVisible(false);
        owner.setVisible(true);
    }//GEN-LAST:event_btCancelActionPerformed

    /**
     * Event triggered when the "Launch" button is pressed in the parameters panel.
     * It creates the SimulParams according to the filled up parameters and then
     * create the SimulationPanel (but doesn't starts the simulation yet!)
     * @param evt  - Event triggered
     */
    private void btLaunchSimulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLaunchSimulActionPerformed

        // checks the parameters
        ISimulParams simParams = null;
        try {
            simParams = getSimParamsFromTextFields();
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Erreur de paramètre", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Asks for generation type
        Object[] options = {"Génération automatique aléatoire", "Génération manuelle"};
        int genTypeOption = JOptionPane.showOptionDialog(this,
                "Comment souhaitez-vous générer la carte ?",
                "Type de génération",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                null);
        if (genTypeOption == JOptionPane.CLOSED_OPTION) {
            return;
        }

        // Asks for random expression if random generation
        boolean random = genTypeOption == JOptionPane.YES_OPTION ? true : false;
        String randomExpr = "10;3;5;3;true";

        if (random) {
            String msg = "Entrez le nombre d'objets maximum à créer séparés par des \";\" (true si nombre exact)"
                    + "\n(Kutis;Stations;Obstacles;Obstacles magn.;isExact(true/false))";
            do {
                randomExpr = (String) JOptionPane.showInputDialog(this, msg, "Maximums", JOptionPane.QUESTION_MESSAGE, null, null, randomExpr);
                if (randomExpr == null) {
                    return;
                }
            } while (!randomExpr.matches("[0-9]+;[0-9]+;[0-9]+;[0-9]+;(true|false)"));
        }

        // sets the generation type and starts the sim
        GenerationType genType = random ? GenerationType.RANDOM_GEN : GenerationType.MANUAL_GEN;
        launchSim(genType, simParams, randomExpr, "");
    }//GEN-LAST:event_btLaunchSimulActionPerformed

    private void launchSim(GenerationType genType, ISimulParams simParams, String randomExpr, String difficulty) {
        new SimulationPanel(this, simParams, genType, randomExpr, difficulty);
    }

    private SimulParams getSimParamsFromTextFields() throws IllegalArgumentException {
        return new SimulParams(
                Double.parseDouble(tfDiameter.getText()),
                Double.parseDouble(tfMaxEnergy.getText()),
                Double.parseDouble(tfInitEnergy.getText()),
                Double.parseDouble(tfKutiSpeedCutterOn.getText()),
                Double.parseDouble(tfKutiSpeedCutterOff.getText()),
                Double.parseDouble(tfMoveEnergy.getText()),
                Double.parseDouble(tfRotationEnergy.getText()),
                Double.parseDouble(tfMowEnergy.getText()),
                Double.parseDouble(tfNoiseFactor.getText()),
                Long.parseLong(tfMaxStep.getText()),
                Double.parseDouble(tfRadarEnergy.getText()),
                Integer.parseInt(tfMessageLength.getText()),
                Integer.parseInt(tfScoreInterval.getText()),
                Double.parseDouble(tfMagnetLibEnergy.getText()),
                Integer.parseInt(tfGrowthPeriod.getText()),
                Integer.parseInt(tfLawnMaxHeight.getText()));
    }

    /**
     * Event triggered when the "Save XML" button is pressed in the parameters panel.
     * Method designed to save all the parameters in an XML file.
     * @param evt - Event triggered
     */
    private void btSaveXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveXMLActionPerformed

        JFileChooser fChooser = new JFileChooser();
        fChooser.setFileFilter(new FileNameExtensionFilter("XML", "xml"));

        if (fChooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
            return;
        }

        Element root = new Element("params");
        Document doc = new Document(root);

        Element kDiameter = new Element("kDiameter");
        kDiameter.setText(tfDiameter.getText());
        root.addContent(kDiameter);

        Element maxEnergy = new Element("kMaxEnergy");
        maxEnergy.setText(tfMaxEnergy.getText());
        root.addContent(maxEnergy);

        Element initEnergy = new Element("kInitialEnergy");
        initEnergy.setText(tfInitEnergy.getText());
        root.addContent(initEnergy);

        Element kSpeedCutOn = new Element("kSpeedCutterOn");
        kSpeedCutOn.setText(tfKutiSpeedCutterOn.getText());
        root.addContent(kSpeedCutOn);

        Element kSpeedCutOff = new Element("kSpeedCutterOff");
        kSpeedCutOff.setText(tfKutiSpeedCutterOff.getText());
        root.addContent(kSpeedCutOff);

        Element moveEnergy = new Element("kMovingEnergy");
        moveEnergy.setText(tfMoveEnergy.getText());
        root.addContent(moveEnergy);

        Element rotEnergy = new Element("kRotationEnergy");
        rotEnergy.setText(tfRotationEnergy.getText());
        root.addContent(rotEnergy);

        Element kCutterEnergy = new Element("kCutterEnergy");
        kCutterEnergy.setText(tfMowEnergy.getText());
        root.addContent(kCutterEnergy);

        Element radarNoiseFactor = new Element("radarNoiseFactor");
        radarNoiseFactor.setText(tfNoiseFactor.getText());
        root.addContent(radarNoiseFactor);

        Element maxSimulationSteps = new Element("maxSimulationSteps");
        maxSimulationSteps.setText(tfMaxStep.getText());
        root.addContent(maxSimulationSteps);

        Element radarEnergy = new Element("radarEnergy");
        radarEnergy.setText(tfRadarEnergy.getText());
        root.addContent(radarEnergy);

        Element messageLength = new Element("messageLength");
        messageLength.setText(tfMessageLength.getText());
        root.addContent(messageLength);

        Element scoreEvalInterval = new Element("scoreEvalInterval");
        scoreEvalInterval.setText(tfScoreInterval.getText());
        root.addContent(scoreEvalInterval);

        Element magnetLiberationEnergy = new Element("magnetLiberationEnergy");
        magnetLiberationEnergy.setText(tfMagnetLibEnergy.getText());
        root.addContent(magnetLiberationEnergy);

        Element bladeGrowthPeriod = new Element("bladeGrowthPeriod");
        bladeGrowthPeriod.setText(tfGrowthPeriod.getText());
        root.addContent(bladeGrowthPeriod);

        Element bladeMax = new Element("bladeMax");
        bladeMax.setText(tfLawnMaxHeight.getText());
        root.addContent(bladeMax);

        File f = fChooser.getSelectedFile();
        if (!f.getAbsolutePath().endsWith(".xml")) {
            f = new File(f.getAbsolutePath() + ".xml");
        }

        try {
            new XMLOutputter(Format.getPrettyFormat()).output(doc, new FileOutputStream(f));
        } catch (Exception ex) {
            Logger.getLogger(ParamPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btSaveXMLActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        owner.setVisible(true);
    }//GEN-LAST:event_formWindowClosing

    private void cbDifficultyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbDifficultyActionPerformed
        if (cbDifficulty.getSelectedIndex() == 0) {
            return;
        }

        String msg = "Cette action entrainera le lancement de la simulation.\n\n Continuer ?";
        switch (JOptionPane.showConfirmDialog(this, msg, "Difficulté préselectionnée", JOptionPane.OK_CANCEL_OPTION)) {
            case JOptionPane.YES_OPTION:
                // continue
                break;
            default:
                cbDifficulty.setSelectedIndex(0);
                return;
        }

        String diff = (String) cbDifficulty.getSelectedItem();
        InputStream is = null;
        if (((String) cbDifficulty.getSelectedItem()).equals("Bac à sable")) {
            is = getClass().getResourceAsStream("/kuti/grp5/ui/resources/samples/params/bac_a_sable.xml");
        } else if (diff.equals("Facile")) {
            is = getClass().getResourceAsStream("/kuti/grp5/ui/resources/samples/params/facile.xml");
        } else if (diff.equals("Moyen")) {
            is = getClass().getResourceAsStream("/kuti/grp5/ui/resources/samples/params/moyen.xml");
        } else if (diff.equals("Difficile")) {
            is = getClass().getResourceAsStream("/kuti/grp5/ui/resources/samples/params/difficile.xml");
        } else if (diff.equals("Brutal")) {
            is = getClass().getResourceAsStream("/kuti/grp5/ui/resources/samples/params/brutal.xml");
        } else {
            return;
        }

        // checks the parameters
        ISimulParams simParams = null;
        try {
            simParams = getSimParamsFromTextFields();
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Erreur de paramètre", JOptionPane.ERROR_MESSAGE);
            cbDifficulty.setSelectedIndex(0);
            return;
        }

        setParametersFromXMLDoc(is,null);
        launchSim(GenerationType.PRESET_GEN, simParams, "", diff);
    }//GEN-LAST:event_cbDifficultyActionPerformed

    /**
     * Sets all the parameters according to the XML File OR InputStream given in parameters
     * @param is - InputStream pointing to an XML file filled with parameters
     * @param f - File pointing to an XML file filled with parameters
     */
    private void setParametersFromXMLDoc(InputStream is, File f) {
        SAXBuilder sxb = new SAXBuilder();
        Document doc = null;
        try {
            doc = f == null ? sxb.build(is) : sxb.build(f);
        } catch (JDOMException ex) {
            Logger.getLogger(ParamPanel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ParamPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        Element root = doc.getRootElement();
        tfDiameter.setText(root.getChildText("kDiameter"));
        tfMaxEnergy.setText(root.getChildText("kMaxEnergy"));
        tfInitEnergy.setText(root.getChildText("kInitialEnergy"));
        tfKutiSpeedCutterOn.setText(root.getChildText("kSpeedCutterOn"));
        tfKutiSpeedCutterOff.setText(root.getChildText("kSpeedCutterOff"));
        tfMoveEnergy.setText(root.getChildText("kMovingEnergy"));
        tfRotationEnergy.setText(root.getChildText("kRotationEnergy"));
        tfMowEnergy.setText(root.getChildText("kCutterEnergy"));
        tfNoiseFactor.setText(root.getChildText("radarNoiseFactor"));
        tfMaxStep.setText(root.getChildText("maxSimulationSteps"));
        tfRadarEnergy.setText(root.getChildText("radarEnergy"));
        tfMessageLength.setText(root.getChildText("messageLength"));
        tfScoreInterval.setText(root.getChildText("scoreEvalInterval"));
        tfMagnetLibEnergy.setText(root.getChildText("magnetLiberationEnergy"));
        tfGrowthPeriod.setText(root.getChildText("bladeGrowthPeriod"));
        tfLawnMaxHeight.setText(root.getChildText("bladeMax"));
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btLaunchSimul;
    private javax.swing.JButton btSaveXML;
    private javax.swing.JComboBox cbDifficulty;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel labTitre;
    private javax.swing.JButton loadXML;
    private javax.swing.JPanel pBts;
    private javax.swing.JPanel pMain;
    private javax.swing.JPanel pParamKuti;
    private javax.swing.JPanel pParamSimul;
    private javax.swing.JPanel pParamTools;
    private javax.swing.JPanel pParams;
    private javax.swing.JPanel pTitleCombo;
    private javax.swing.JPanel pTitre;
    private javax.swing.JSeparator sepTitre;
    private javax.swing.JTextField tfDiameter;
    private javax.swing.JTextField tfGrowthPeriod;
    private javax.swing.JTextField tfInitEnergy;
    private javax.swing.JTextField tfKutiSpeedCutterOff;
    private javax.swing.JTextField tfKutiSpeedCutterOn;
    private javax.swing.JTextField tfLawnMaxHeight;
    private javax.swing.JTextField tfMagnetLibEnergy;
    private javax.swing.JTextField tfMaxEnergy;
    private javax.swing.JTextField tfMaxStep;
    private javax.swing.JTextField tfMessageLength;
    private javax.swing.JTextField tfMoveEnergy;
    private javax.swing.JTextField tfMowEnergy;
    private javax.swing.JTextField tfNoiseFactor;
    private javax.swing.JTextField tfRadarEnergy;
    private javax.swing.JTextField tfRotationEnergy;
    private javax.swing.JTextField tfScoreInterval;
    // End of variables declaration//GEN-END:variables
}